<?php

include 'app/webmail.php';

$oInputData = new CInputData();

$oAccount = CAccount::CreateAccountFromHash($oInputData->GetCookieValue('xwm_auth', ''));
if ($oAccount)
{
	$oWebMail = new CCoreLabsWebMail($oAccount);

	$sFolderFullName = $oInputData->GetQueryValue('folder', '');
	$sUid = $oInputData->GetQueryValue('uid', '');
	
	if (!empty($sFolderFullName) && !empty($sUid))
	{
		switch ($oInputData->GetQueryValue('action', ''))
		{
			case 'attachment':
				if ($oInputData->ServerNotModifiedCache(31536000))
				{
					exit();
				}
				
				$sMimeIndex = $oInputData->GetQueryValue('index', '');
				try
				{
					$oWebMail->AttachmentThroughCallback(
						$sFolderFullName, $sUid, $sMimeIndex, 'getAttachmentCallback');
				}
				catch (CCoreWebMailProtocolsIncException  $oException)
				{
					echo $oException->getMessage();
				}
				break;

			case 'save':
				try
				{
					@header('Content-Disposition: attachment; filename="'.$sUid.'.eml";	charset="'.C_MIME_CHARSET_UTF8.'"');
					@header('Content-Type: text/plain');
					
					$oWebMail->MessageFullBodyThroughCallback(
						$sFolderFullName, $sUid, 'getAttachmentMessageCallback');
				}
				catch (CCoreWebMailProtocolsIncException  $oException)
				{
					echo $oException->getMessage();
				}
				break;
			
			case 'headers':
				try
				{
					@header('Content-Type: text/plain');
					echo $oWebMail->MessageFullHeaders($sFolderFullName, $sUid);
				}
				catch (CCoreWebMailProtocolsIncException  $oException)
				{
					echo $oException->getMessage();
				}
				break;
		}
	}
}

exit();

/**
 * @param CCoreLabsWebMailAttachment $oAttachment
 * @param resource $rStream
 */
function getAttachmentCallback(CCoreLabsWebMailAttachment $oAttachment, $rStream)
{
	@header('Content-Disposition: attachment; filename="'.
		CCoreBaseUtils::ClearFileName($oAttachment->FileName).
		'"; charset="'.C_MIME_CHARSET_UTF8.'"');
	@header('Content-Type: '.$oAttachment->MimeType);

	fpassthru($rStream);
}

/**
 * @param resource $rStream
 */
function getAttachmentMessageCallback($rStream)
{
	fpassthru($rStream);
}
